package org.road0329.dlt698.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;
import org.road0329.dlt698.asn1.axdr.AxdrEnum;
import org.road0329.dlt698.asn1.axdr.AxdrOptional;
import org.road0329.dlt698.asn1.axdr.AxdrType;

import java.io.IOException;
import java.nio.ByteBuffer;

public class RETOMDDATA extends AxdrType {
    private ByteBuffer dataCode = null;
    private OMD omd = null;
    private AxdrEnum dar = null;
    private AxdrOptional<Data> retData = new AxdrOptional<>(new Data(), false);

    public RETOMDDATA() {
    }

    public ByteBuffer getDataCode() {
        return dataCode;
    }

    public OMD getOmd() {
        return omd;
    }

    public AxdrEnum getDar() {
        return dar;
    }

    public AxdrOptional<Data> getRetData() {
        return retData;
    }

    public void setDataCode(ByteBuffer dataCode) {
        this.dataCode = dataCode;
    }

    public void setAll(OMD omd, AxdrEnum dar, Data retData) {
        this.omd = omd;
        this.dar = dar;
        this.retData.setValue(retData);
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        this.omd = new OMD();
        codeLength += this.omd.decode(input);
        this.dar = new AxdrEnum();
        this.dar.setConst();
        codeLength += this.dar.decode(input);
        this.retData = new AxdrOptional<>(new Data(), false);
        codeLength += this.retData.decode(input);
        return codeLength;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength;
        if (this.dataCode != null) {
            codeLength = this.dataCode.remaining();
            while (this.dataCode.hasRemaining()) {
                output.write(this.dataCode.get());
            }
        } else {
            if (this.dar != null && this.omd != null && this.retData != null) {
                codeLength = 0;
                codeLength += this.retData.encode(output);
                codeLength += this.dar.encode(output);
                codeLength += this.omd.encode(output);
            } else {
                throw new IllegalStateException("retData, dar, or omd is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) throws Exception {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = ByteBuffer.wrap(revOStream.toByteArray());
    }

    @Override
    public String toString() {
        if (this.omd != null && this.dar != null && this.retData != null) {
            return "sequence: {" + "omd: " + this.omd + ", dar: " + this.dar + ", retData: " + this.retData + "}";
        } else {
            return "retData, dar, or omd is null";
        }
    }
}



